<template>
  <div ref="chartRef" :style="{ width: props.width, height: props.height }"></div>
</template>

<script setup lang="ts">
  import { onMounted, ref,onBeforeUnmount, watch } from 'vue';
  import * as echarts from 'echarts';
  import type { ECharts } from 'echarts';

  const props = defineProps({
    options: {
      type: Object,
      required: true,
    },
    width: {
      type: String,
      default: '100%',
    },
    height: {
      type: String,
      default: '400px',
    },
  })
  // 定义 ref
  const chartRef = ref(null);
  let chartInstance:ECharts | null = null;

  // 初始化图表
  const initChart = () => {
    chartInstance = echarts.init(chartRef.value);
    chartInstance.setOption(props.options);
  };

  // 更新图表选项
  const updateChart = () => {
    if (chartInstance) {
      chartInstance.setOption(props.options);
    }
  };

  // 处理窗口大小变化
  const resizeChart = () => {
    if (chartInstance) {
      chartInstance.resize();
    }
  };

  // 组件挂载时
  onMounted(() => {
    initChart();
    window.addEventListener('resize', resizeChart);
  });

  // 组件卸载时
  onBeforeUnmount(() => {
    if (chartInstance) {
      chartInstance.dispose();
    }
    window.removeEventListener('resize', resizeChart);
  });

  // 监听 props.options 的变化
  watch(
    () => props.options,
    (newOptions) => {
      updateChart();
    },
    { deep: true }
  );
</script>
